// shop page
// ============

define(['zepto', 'utils', 'JST', 'page/mobile-bind', 'page/trading/coupon-select', 'amountControl'], function($, utils, JST, mobileApp, couponSelect) {
  return {
    init: function(data) {

      this.onOrderAmountChange()
      this.bindOrderSubmitAction()
      this.onCouponChange()
      this.model = {
        'product': data.product,
      }
      mobileApp.init(__CTX__);
      couponSelect.init(__CTX__, 1)
    },

    // order amount change handler
    onOrderAmountChange: function() {

      that = this
      
      var $orderAmountInput = $("input[name='quantity']")

      $orderAmountInput.on("amountcontrol:change", function(e){
        var amount = $(this).val(), price= that.model.product.amount
        var couponAmount = $('[href="#coupon-select"]').find('.item-after').data('coupon-amount')
        that.calculateAmount(amount, price, couponAmount)
      })
    },

    // coupon select change handler
    onCouponChange: function() {

      that = this
      var $orderAmountInput = $("input[name='quantity']"), $totalCost=$(".total-cost")

      $(document).on('coupon:change:event', '[href="#coupon-select"]', function(event) {
        event.preventDefault()
        var couponAmount = $(this).find('.item-after').data('coupon-amount')
        var amount = $($orderAmountInput).val(), price= that.model.product.amount
        that.calculateAmount(amount, price, couponAmount)
      })
    },

    // calculate total cost
    calculateAmount: function(amount, price, couponAmount) {
      var $totalCost=$(".total-cost")
      var cost = ( price * amount)
      if (couponAmount != undefined && couponAmount != null) {
        cost = ( price * amount )  -couponAmount > 0 ? (( price * amount )  -couponAmount) : 0;
      }
      $totalCost.text((cost / 100).toFixed(0))
    },

    // order submit evvent handler
    bindOrderSubmitAction: function() {
      
      that = this
      
      var submitButton = $("a.button-order")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = that.onInitData()
        // validate all input
        if(that.onValidateData(data)) {
          // do submit order with data
          data = that.onAppendData(data)
          that.onSubmitOrder(data)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        'productId': {
          'value': this.model.product.id,
          'message': '产品id不能为空'
        },
        'contactName': {
          'value': $('input[name="contactName"]').val().trim(),
          'message': '请填写联系人姓名'
        },
        'contactMobile': {
          'value': $('input[name="contactMobile"]').val().trim(),
          'message': '请填写联系人手机'
        },
        'amount': {
          'value': $('input[name="quantity"]').val().trim(),
          'message': '数量不能为空'
        }
      }

    },

    onAppendData: function(data) {
      
      data.couponId = {
        'value': $('[href="#coupon-select"]').find('.item-after').data('selected-coupon')
      }
      data.comment = {
        'value': $('textarea[name="comment"]').val()
      }
      return data;
    },

    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      if (!this.isChinese(data.contactName.value)) {
        return $.toast('请填写正确的联系人姓名')
      }

      if (data.amount.value == 0) {
        return $.toast('请填写正确的数量') 
      }

      return true
    },

    /**
     * Check value is Chinese character
     */
    isChinese: function(value) {
      return /[^\u0000-\u00FF]/.test(value)
    },
    
    onSubmitOrder: function(data) {
      $.showPreloader('正在提交订单')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/orders',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('创建订单成功')
          setTimeout(function() {
            window.location.href = __CTX__.root + '/pay?order=' + result.data.orderId
          }, 1000)
        }, function(result) {
          $.toast(result.message || '订单创建失败')
        })
      })
      
    }
  }
})